package com.talkyun.utils;

import java.net.URL;

import static java.io.File.separator;

/**
 * @author k1024
 */
public class UrlJoiner {

    public String join(String url, String uri) {
        if (url == null || uri == null) {
            return url == null ? (uri == null ? null : uri.trim()) : url.trim();
        }

        url = url.trim();
        uri = uri.trim();
        uri = uri.startsWith("/") ? uri : "/" + uri;

        try {
            return new URL(url + uri).toURI().normalize().toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String joinQuery(String url, String qs) {
        if (qs == null || qs.trim().length() == 0) {
            return url == null ? null : url.trim();
        }

        try {
            URL fmtUrl = new URL(url);
            String split = fmtUrl.getQuery() == null ? "?" : "&";

            return fmtUrl.toURI().normalize().toString() + split + qs.trim();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String joinFilePath(String dirPath, String filePath) {
        if (dirPath.endsWith(separator)) {
            return filePath.startsWith(separator) ? dirPath + filePath.substring(1) : dirPath + filePath;
        } else {
            return filePath.startsWith(separator) ? dirPath + filePath : dirPath + separator + filePath;
        }
    }

    public static void main(String[] args) {

        // URL url = new URL("https://www.baidu.com/s?wd=java%20url%20%E6%B8%85%E6%A5%9A%E5%A4%9A%E4%BD%99%E7%9A%84%20%2F&pn=30&oq=java%20url%20%E6%B8%85%E6%A5%9A%E5%A4%9A%E4%BD%99%E7%9A%84%20%2F&tn=baiduhome_pg&ie=utf-8&rsv_idx=2&rsv_pq=ec05f5dc000170f6&rsv_t=ec09%2BWpgNvXqzBrnJ%2FQGA3IvL6xmnDhkjZ9v2qcf5ny0JHHNNKUSGaUXVDbmGGYzCSwI");
        // System.out.println(url.toURI().normalize().toString());

        UrlJoiner uj = new UrlJoiner();
        System.out.println(uj.join("https://www.baidu.com/s/ddd/", "/home"));

        System.out.println(uj.joinQuery("https://www.baidu.com/s?ddd", "dfadf&dfaf"));

    }
}